package com.cooper.scraper.show;

import java.util.ArrayList;
import java.util.List;

import com.cooper.scraper.R;
import com.cooper.scraper.ResourceCollector;
import com.cooper.scraper.ResourceScraperRunner;
import com.cooper.scraper.RunnerSubscribe;
import com.cooper.scraper.ScraperBrowseParam;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class OnlineResourceAdapter<T extends OnlineFanartResource> extends
		FanartAdapter<T> implements RunnerSubscribe {

	protected Context context;

	private List<T> resources = new ArrayList<T>();

	private ResourceScraperRunner<T> runner;
	private boolean downloading = false;
	private ResourceCollector<T> mediaCollector;

	private int maxRequestPos = 0;

	public OnlineResourceAdapter(Context context,
			ResourceScraperRunner<T> runner, ResourceCollector<T> mediaCollector) {
		super();
		this.context = context;
		this.mediaCollector = mediaCollector;
		this.runner = runner;
		runner.subscribe(this);
	}

	public OnlineResourceAdapter(Context context, ResourceScraperRunner<T> runner) {
		super();
		this.context = context;
		this.runner = runner;
		runner.subscribe(this);
	}

	public void setResourceCollector(ResourceCollector<T> mediaCollector) {
		if (this.mediaCollector != null)
			runner.cancel(this);

		this.mediaCollector = mediaCollector;
	}

	public ResourceCollector<T> getResourceCollection() {
		return mediaCollector;
	}

	@Override
	public void refresh() {
		if (mediaCollector == null) {
			return;
		}
		runner.cancel(this);
		destroyResources();
		resources.clear();
		mediaCollector.reset();
		fanartsShow.resetFanart();
		notifyDataSetChanged();

		runner.listResource(context, mediaCollector);
		downloading = true;
		if (dataChangedListener != null)
			dataChangedListener.dataWaiting();

	}

	private void prepareNextPage() {
		if (mediaCollector == null) {
			return;
		}
		if (!downloading && mediaCollector.hasNextPage()
				&& (maxRequestPos >= (resources.size() - 1))) {
			mediaCollector.nextPage();

			runner.listResource(context, mediaCollector);
			downloading = true;
			if (dataChangedListener != null)
				dataChangedListener.dataWaiting();

		}
	}

	@Override
	public void destroy() {
		runner.cancelSubscribe(this);
		destroyResources();
	}

	@Override
	public int getCount() {
		return resources.size();
	}

	@Override
	public Object getItem(int position) {
		return resources.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	protected T getResource(int position) {
		return resources.get(position);
	}

	@Override
	protected void onShowView(T resource, int position) {
		if (position > maxRequestPos) {
			maxRequestPos = position;
		}
		prepareNextPage();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onDownloadComplete(String key, Object data) {
		ResourceCollector<T> result = (ResourceCollector<T>) data;
		downloading = false;
		if (!result.noResult()) {
			resources.addAll(result.getMedias());
			for (OnlineFanartResource resource: result.getMedias()){
				runner.downloadBitmap(
						resource.getFanartUrl(),
						resource.getReferer(),
						OnlineFanartResource.DOWNLOAD_FANART_KEY_PREFIX
								+ resource.getFanartUrl());
			}
			
			Log.d("OnlineMovieFanartAdapter",
					"downloadComplete:" + resources.size());
			notifyDataSetChanged();
			prepareNextPage();

		} else if (resources.isEmpty() && dataChangedListener != null) {

			dataChangedListener.noResultData();
		}
		if (!downloading && (dataChangedListener != null))
			dataChangedListener.dataComplete();
	}

	@Override
	public void onDownloadFail(String key, int errorCode) {
		// resultMedias.nextPage();?????

		downloading = false;
		if (dataChangedListener != null) {
			if (resources.isEmpty()) {
				dataChangedListener.noResultData();
			}
			dataChangedListener.dataComplete();
		}
		Toast.makeText(
				context,
				context.getResources().getString(
						R.string.toast_download_next_page_fail),
				Toast.LENGTH_LONG).show();

	}

	@Override
	public void onDownloadCancel(String key) {
	}

	@Override
	public boolean subscribed(String key) {
		if (mediaCollector != null) {
			return mediaCollector.subscribed(key);
		} else
			return false;
	}

	private void destroyResources() {
		for (T resource : resources) {
			resource.destroy();
		}
	}

	@Override
	public void setSearchKeyword(String keyword) {
		mediaCollector.putParams(new ScraperBrowseParam(keyword));
	}
	
	

}
